﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web;
using System.Configuration;

namespace WISD.Common
{
    public class BasePage : System.Web.UI.Page
    {
        /// <summary>
        /// 取得ViewState中的值
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="name">名称</param>
        /// <returns>值</returns>
        protected T VS<T>(string name)
        {
            object o = ViewState[name];
            if (o == null)
            {
                return default(T);
            }
            return (T)Convert.ChangeType(o, typeof(T));
        }

        /// <summary>
        /// 设置ViewState的值
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="name">名称</param>
        /// <param name="value">值</param>
        protected void VS<T>(string name, T value)
        {
            ViewState[name] = value;
        }

        /// <summary>
        /// 转化QueryString的值
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="queryKey">Key</param>
        /// <returns>值</returns>
        protected T QueryString<T>(string queryKey)
        {
            string value = Request.Params[queryKey];
            try
            {                
                return (T)Convert.ChangeType(value, typeof(T));
            }
            catch
            {
                throw new Exception("参数错误");
            }
        }

        /// <summary>
        /// Try-Catch
        /// </summary>
        /// <param name="action">方法</param>
        protected bool Try(Action action)
        {
            return Try(action, null);
        }

        /// <summary>
        /// Try-Catch
        /// </summary>
        /// <param name="action">方法</param>
        /// <param name="redirectUrl">出错后跳转到的页面</param>
        protected bool Try(Action action,string redirectUrl)
        {
            try
            {
                if (action != null)
                {
                    action();
                }
                return true;
            }
            catch (Exception ex)
            {
                if (!string.IsNullOrEmpty(redirectUrl)) //跳转
                {
                    ShowAndRedirectAjax("up", ex.Message, redirectUrl);
                }
                else //弹出错误
                {
                    AjaxAlert(ex.Message);
                }
                return false;
            }
        }

        /// <summary>
        /// 获得上层控件上所有的子控件
        /// </summary>
        /// <typeparam name="T">控件类型如TextBox</typeparam>
        /// <param name="control"></param>
        /// <returns></returns>
        public List<T> GetControl<T>(Control control)
            where T : Control
        {
            List<T> list = new List<T>();
            foreach (Control c in control.Controls)
            {
                if (c is T)
                {
                    list.Add(c as T);
                }
                list = list.Union(GetControl<T>(c)).ToList(); //对每个子控件递归
            }
            return list;
        }


        /// <summary>
        /// 在AJAX页面上以alert弹出一个字符串
        /// </summary>
        /// <param name="msg">弹出的字符串</param>
        public void AjaxAlert(string msg)
        {
            string new_msg = string.IsNullOrEmpty(msg) ? string.Empty :
            Microsoft.JScript.GlobalObject.escape(msg);
            // msg.Replace("'", string.Empty);
            System.Web.UI.ScriptManager.RegisterClientScriptBlock(this.Page,
                this.GetType(), Guid.NewGuid().ToString(),
                string.Format("alert(unescape('{0}'));", new_msg), true);
        }
        /// <summary>
        /// as the title,show the message and then redirect to cetain url
        /// </summary>
        /// <param name="panel">最外围updatepanel的ID</param>
        /// <param name="msg">the message which is preparing to show</param>
        /// <param name="url">the url which you want to</param>
        public void ShowAndRedirectAjax(string panel, string msg, string url)
        {
            System.Web.UI.ScriptManager.RegisterClientScriptBlock((UpdatePanel)Master.FindControl("UpdatePanel1"),
                                this.GetType(), Guid.NewGuid().ToString(),
                                string.Format("{0}", "alert(unescape('" + Microsoft.JScript.GlobalObject.escape(msg) + "'));window.location=\"" + url + "\""), true);
            // System.Web.UI.ScriptManager.RegisterStartupScript(this.Page, this.GetType(), Guid.NewGuid().ToString(), "<script language='javascript' defer>alert('" + msg + "');window.location=\"" + url + "\"</script>", true);
        }

        /// <summary>
        /// 用于临时记录数据量的一个属性
        /// </summary>
        public int totalCount
        {
            get { return (int)ViewState["totalCount"]; }
            set { ViewState["totalCount"] = value; }
        }
        /// <summary>
        /// 分页索引
        /// </summary>
        public int pageIndex
        {
            get { return (int)ViewState["pageIndex"]; }
            set { ViewState["pageIndex"] = value; }
        }

        /// <summary>
        /// 元数据库的连接
        /// </summary>
        public static string metaString
        {
            get { return ConfigurationManager.ConnectionStrings["MetaEntities"].ConnectionString; }
        }
        /// <summary>
        /// 用以判断一个ID类的参数不能为空
        /// </summary>
        /// <param name="name">参数名</param>
        /// <param name="toValue">参数值</param>
        public void doJudgement(string name, string toValue)
        {
            int num = 0;
            if (string.IsNullOrEmpty(toValue) || !int.TryParse(toValue, out num))
            {
                //this.ShowAndRedirectAjax("UpdatePanel1", "参数" + name + "不能为空，请确认！", "Default.aspx");
                Response.Redirect("Default.aspx");

            }
        }
    }
}
